package com.dongliu.controller;


import com.dongliu.domain.Admin;
import com.dongliu.domain.LentRecord;
import com.dongliu.domain.User;
import com.dongliu.service.LentRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/lentRecords")
public class LentRecordsController {
    @Autowired
    private LentRecordService lentRecordService;

    @PostMapping
    public Result save(@RequestBody LentRecord lentRecord) {
        System.out.println(lentRecord);
        boolean flag = lentRecordService.save(lentRecord);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody LentRecord lentRecord) {
        boolean flag = lentRecordService.update(lentRecord);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR, flag);
    }

    @DeleteMapping("/{lentId}")
    public Result delete(@PathVariable Integer lentId) {
        boolean flag = lentRecordService.delete(lentId);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR, flag);
    }

    @GetMapping("/{lentId}")
    public Result getByLentId(@PathVariable Integer lentId) {
        LentRecord lentRecord = lentRecordService.getByLentId(lentId);
        Integer code = lentRecord != null ? Code.GET_OK : Code.GET_ERR;
        String msg = lentRecord != null ? "" : "数据查询失败，请重试！";
        return new Result(code, lentRecord, msg);
    }

    @GetMapping
    public Result getAll(HttpServletRequest request) {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        User user = (User) request.getSession().getAttribute("user");
        if(admin == null && user == null)
            return new Result(Code.LOGIN_ERR, null, "请登录后再执行操作！");
        List<LentRecord> lentRecordList = lentRecordService.getAll();
        Integer code = lentRecordList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = lentRecordList != null ? "":"数据查询失败，请重试！";
        return new Result(code, lentRecordList, msg);
    }
}
